package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.logicException;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.Lead;
import cn.wolfcode.util.UserContextUtil;
import cn.wolfcode.qo.QueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper ;
    @Autowired
    private DepartmentMapper departmentMapper ;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteEmpANdRole(id);
    }

    @Override
    public void update(Employee employee,Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //修改时把之前的角色关系全部删掉
        employeeMapper.deleteEmpANdRole(employee.getId());
        //删完之后在添加新的角色关系
        if (ids!=null){
            //为中间表添加关系
            for (Long id : ids) {
                employeeMapper.insertEmpANdRole(employee.getId(), id);
            }
        }
    }

    @Override
    public void insert(Employee employee,Long[] ids) {
        employeeMapper.insert(employee);
        if (ids!=null){
            //为中间表添加关系
            for (Long id : ids) {
                employeeMapper.insertEmpANdRole(employee.getId(), id);
            }
        }
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());

        return new PageInfo<>(employeeMapper.query(qo));
    }

    @Override
    public Employee login(String username, String password) {
        List<Employee> employees = employeeMapper.selectAll();
        if (!StringUtils.hasText(username)){
            throw new logicException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)){
            throw new logicException("用密码不能为空");
        }
        Employee loginEmp =null;
        for (Employee e:employees) {
            //用户名正确
            if (e.getUsername().equals(username)){
                //密码也正确
                if (e.getPassword().equals(password)){
                    //登录成功
                    if (e.isStatus()){
                        //员工状态也正常
                        loginEmp =e;
                    }else {
                        throw new logicException("用户状态异常,请联系管理员");
                    }
                }else {
                    //密码不正确
                    throw new logicException("密码不正确");
                }
            }
        }
        if (loginEmp == null){
            throw  new logicException("此用户不存在");
        }
       return loginEmp;
    }

    @Override
    public void alterPassword(String oldPassword, String newPassword, Long id) {
        //更改密码操作
        //先通过ID查出员工
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        //对比输入的旧密码是不是一样
        if (employee.getPassword().equals(oldPassword)){
            //新密码不是空
            if (StringUtils.hasText(newPassword)){
                //如果密码一样那把新密码替换掉新密码
                employee.setPassword(newPassword);
                //再重修修改员工数据
                employeeMapper.updatePassword(employee);
            }else {
                throw new logicException("新密码不能为空");
            }

        }else {
            throw new logicException("原始密码不正确");
        }
    }

    @Override
    public List<String> selectByPermission(Long id) {
        return employeeMapper.selectByPermission(id);
    }

    @Override
    public Employee checkName(String username) {
        return  employeeMapper.checkName(username);
    }

    @Override
    public Workbook exportXls() {
        //先把所有员工查询出来
        List<Employee> employees = employeeMapper.selectAll();
        Workbook wb = new HSSFWorkbook(); //创建一个工作本 普通版
        Sheet sheet = wb.createSheet("员工信息表单");//创建工作表
        Row row = sheet.createRow(0);//首行写标题
        row.createCell(0).setCellValue("姓名"); //第一行第一列是名字标题
        row.createCell(1).setCellValue("年龄"); //第一行第二列是年龄标题
        row.createCell(2).setCellValue("部门"); //第一行第三列是部门标题
        row.createCell(3).setCellValue("邮箱"); //第一行第四列是邮箱标题
        //遍历员工一行一行写到表格里
        for (int i = 0; i < employees.size(); i++) {
            row = sheet.createRow(i+1);//每次都往下一行
            Employee employee = employees.get(i);
            row.createCell(0).setCellValue(employee.getName()); //第一行第一列是名字标题
            if (employee.getAge() != null){
                row.createCell(1).setCellValue(employee.getAge()); //第一行第二列是年龄标题}
            }
            row.createCell(2).setCellValue(employee.getDept().getName()); //第一行第三列是部门标题
            row.createCell(3).setCellValue(employee.getEmail()); //第一行第四列是邮箱标题
        }
        return wb;
    }

    @Override
    public List<String> importXls(MultipartFile file) throws IOException {
        //正确的个数
        int succeedCount = 0;
        //错误的个数
        int errorCount = 0 ;
        //错误异常集合
        ArrayList<String> exceptions = new ArrayList<>();
        //通过传过来的file 获取到一个工作簿
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //获取工作簿中的工作表
        Sheet sheet = wb.getSheetAt(0);
        //读取最后一行,就能知道有多少条数据
        int lastRowNum = sheet.getLastRowNum();
        //开始循环写入数据库
        for (int i = 1; i <= lastRowNum; i++) {
            try {
                Lead.examine(sheet,i);//进行数据验证
                succeedCount++;
            }catch (Exception e){
                errorCount++;
                exceptions.add(e.getMessage());
            }
            Department department = departmentMapper.selectByPrimaryName(Lead.deptName);
            Employee employee = new Employee();
            //固定密码888
            employee.setPassword("888");
            employee.setUsername(Lead.username);
            employee.setName(Lead.Name);
            employee.setAge(Lead.age);
            employee.setEmail(Lead.email);
            employee.setDept(department);
            employeeMapper.insert(employee);
        }
        UserContextUtil.setSucceedCount(succeedCount);
        UserContextUtil.setErrorCount(errorCount);
        return exceptions;
    }

    @Override
    public void repeatPassword(Long id) {
        employeeMapper.repeatPassword(id);
    }

    @Override
    public void alterStatus(Employee employee) {
        employeeMapper.alterStatus(employee);
    }
}
